package com.mail.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.mail.commons.utils.JwtUtils;
import com.mail.commons.utils.UserHolder;
import com.mail.model.db.UmsAdmin;
import com.mail.server.common.R;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * @author 吕永乐
 * @date 2022/06/21 09:59
 **/
public class TokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//1、获取请求头
		String token = request.getHeader("Authorization").split(" ")[1];
		//2、使用工具类，判断token是否有效
		boolean verifyToken = JwtUtils.verifyToken(token);
		//3、如果token失效，返回状态码401，拦截
		if(!verifyToken){
			response.setStatus(401);
			response.getWriter().write(JSON.toJSONString(R.error("", 401)));
			return false;
		}
		//4、如果token正常可用，放行
		//解析token，获取id和用户名，构造User对象，存入Threadlocal
		Claims claims = JwtUtils.getClaims(token);
		Integer id = (Integer) claims.get("id");
		String username = (String) claims.get("username");
		UmsAdmin user = new UmsAdmin();
		user.setId(Long.valueOf(id));
		user.setUsername(username);
		UserHolder.set(user);
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		UserHolder.remove();
	}
}
